{
  "name": "Case 49: Customs Classification & Duty Estimator",
  "nodes": [
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "triggerOn": "specificFolder",
        "folderToWatch": {
          "__rl": true,
          "value": "1ILOT1s1L-L_FAj5xCefv4yTL2F_M0F1Z",
          "mode": "list",
          "cachedResultName": "Case 49 - Bill of Lading Folder",
          "cachedResultUrl": "https://drive.google.com/drive/folders/1ILOT1s1L-L_FAj5xCefv4yTL2F_M0F1Z"
        },
        "event": "fileCreated",
        "options": {}
      },
      "id": "0dfc2cf4-e9fe-4ad7-a71a-f7fe7eb87fa6",
      "name": "Monitor BoL Upload Folder",
      "type": "n8n-nodes-base.googleDriveTrigger",
      "typeVersion": 1,
      "position": [
        -1136,
        -48
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "Cf6MNES8JrQntp3r",
          "name": "Google Drive account"
        }
      }
    },
    {
      "parameters": {
        "operation": "download",
        "fileId": {
          "__rl": true,
          "value": "={{ $json.id }}",
          "mode": "id"
        },
        "options": {}
      },
      "id": "1a55f61c-1f8f-4485-8f21-3e255f33aedb",
      "name": "Download BoL Document",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        -944,
        -48
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "Cf6MNES8JrQntp3r",
          "name": "Google Drive account"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.cloud.llamaindex.ai/api/v1/parsing/upload",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer llx-7BWYrvPwfUhgdXbZMtaNCsr2O0h7JH4dkHjHisxcvq46bkIj"
            }
          ]
        },
        "sendBody": true,
        "contentType": "multipart-form-data",
        "bodyParameters": {
          "parameters": [
            {
              "parameterType": "formBinaryData",
              "name": "file",
              "inputDataFieldName": "data"
            }
          ]
        },
        "options": {}
      },
      "id": "2fee1572-ee52-4801-b0eb-2f85354c5b3a",
      "name": "Upload to Parser",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -752,
        -48
      ]
    },
    {
      "parameters": {
        "amount": 20
      },
      "id": "d8d179e4-c954-44bf-aeb3-18aa2e4617a5",
      "name": "Wait for Parsing",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        -560,
        -48
      ],
      "webhookId": "e594eb78-ab1f-4f7e-9b25-6786af06e075"
    },
    {
      "parameters": {
        "url": "=https://api.cloud.llamaindex.ai/api/v1/parsing/job/{{ $node[\"Upload to Parser\"].json[\"id\"] }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer llx-7BWYrvPwfUhgdXbZMtaNCsr2O0h7JH4dkHjHisxcvq46bkIj"
            }
          ]
        },
        "options": {}
      },
      "id": "884538f6-2766-4af3-aa49-b4526e849297",
      "name": "Check Parsing Status",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -336,
        -48
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "conditions": [
                  {
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "SUCCESS",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              },
              "renameOutput": true,
              "outputKey": "SUCCESS"
            },
            {
              "conditions": {
                "conditions": [
                  {
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "PENDING",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              },
              "renameOutput": true,
              "outputKey": "PENDING"
            }
          ]
        },
        "options": {}
      },
      "id": "32e5b0cc-af8b-44fe-93a7-182bf7067ee0",
      "name": "Route Based on Status",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.3,
      "position": [
        -112,
        -48
      ]
    },
    {
      "parameters": {
        "url": "=https://api.cloud.llamaindex.ai/api/v1/parsing/job/{{ $node[\"Upload to Parser\"].json[\"id\"] }}/result/markdown",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer llx-7BWYrvPwfUhgdXbZMtaNCsr2O0h7JH4dkHjHisxcvq46bkIj"
            }
          ]
        },
        "options": {}
      },
      "id": "8f5da7b7-a1e3-47fb-b1ef-10c0334c1c37",
      "name": "Extract Parsed Content",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        128,
        -144
      ]
    },
    {
      "parameters": {
        "text": "={{ $json.markdown }}",
        "attributes": {
          "attributes": [
            {
              "name": "BoL_Number",
              "description": "The Bill of Lading reference number"
            },
            {
              "name": "Commodity_Description",
              "description": "Detailed description of goods being shipped"
            },
            {
              "name": "HS_Code",
              "description": "The Harmonized System code (6-10 digits)"
            },
            {
              "name": "Country_of_Origin",
              "description": "Country where goods were manufactured or produced"
            },
            {
              "name": "Destination_Country",
              "description": "Country where goods are being imported to"
            },
            {
              "name": "Declared_Value_USD",
              "description": "Total declared customs value in USD"
            },
            {
              "name": "Gross_Weight_KG",
              "description": "Total gross weight in kilograms"
            },
            {
              "name": "Number_of_Packages",
              "description": "Total number of packages or cartons"
            }
          ]
        },
        "options": {}
      },
      "id": "c6d892dc-38c0-436e-a31d-983a29092cfe",
      "name": "AI Data Extractor",
      "type": "@n8n/n8n-nodes-langchain.informationExtractor",
      "typeVersion": 1.2,
      "position": [
        304,
        -144
      ]
    },
    {
      "parameters": {
        "jsCode": "const bolData = $input.first().json.output;\n\n// ROBUST NUMBER EXTRACTION FUNCTION\nconst extractNumber = (str) => {\n  if (!str) return 0;\n  const cleaned = str.toString().replace(/[^\\d.-]/g, '');\n  const num = parseFloat(cleaned);\n  return isNaN(num) ? 0 : num;\n};\n\n// EMBEDDED HS CODE CLASSIFICATION DATABASE\nconst hsCodeDatabase = {\n  // Chapter 30: Pharmaceutical products\n  \"3004\": {\n    description: \"Medicaments (excluding goods of heading 30.02, 30.05 or 30.06)\",\n    category: \"Pharmaceuticals\",\n    typical_keywords: [\"medicine\", \"tablet\", \"capsule\", \"pharmaceutical\", \"drug\", \"ayurvedic\", \"supplement\"]\n  },\n  \"3003\": {\n    description: \"Medicaments consisting of two or more constituents mixed together\",\n    category: \"Pharmaceuticals\",\n    typical_keywords: [\"herbal\", \"ayurveda\", \"supplement\", \"health\"]\n  },\n  \n  // Chapter 84: Machinery and mechanical appliances\n  \"8471\": {\n    description: \"Automatic data processing machines and units thereof\",\n    category: \"Electronics\",\n    typical_keywords: [\"computer\", \"laptop\", \"server\", \"processor\", \"hardware\"]\n  },\n  \"8473\": {\n    description: \"Parts and accessories for machines of heading 84.71\",\n    category: \"Electronics\",\n    typical_keywords: [\"computer parts\", \"keyboard\", \"mouse\", \"monitor\"]\n  },\n  \n  // Chapter 85: Electrical machinery and equipment\n  \"8517\": {\n    description: \"Telephone sets, including smartphones and other apparatus\",\n    category: \"Electronics\",\n    typical_keywords: [\"phone\", \"smartphone\", \"mobile\", \"telephone\"]\n  },\n  \"8528\": {\n    description: \"Monitors and projectors, not incorporating television reception apparatus\",\n    category: \"Electronics\",\n    typical_keywords: [\"monitor\", \"display\", \"screen\", \"projector\"]\n  },\n  \n  // Chapter 61: Articles of apparel and clothing accessories, knitted\n  \"6109\": {\n    description: \"T-shirts, singlets and other vests, knitted or crocheted\",\n    category: \"Textiles\",\n    typical_keywords: [\"t-shirt\", \"tshirt\", \"vest\", \"garment\", \"clothing\"]\n  },\n  \"6110\": {\n    description: \"Jerseys, pullovers, cardigans, waistcoats and similar articles\",\n    category: \"Textiles\",\n    typical_keywords: [\"sweater\", \"pullover\", \"cardigan\", \"jersey\"]\n  },\n  \n  // Chapter 73: Articles of iron or steel\n  \"7308\": {\n    description: \"Structures and parts of structures, of iron or steel\",\n    category: \"Industrial\",\n    typical_keywords: [\"steel structure\", \"metal frame\", \"iron\", \"construction\"]\n  },\n  \n  // Chapter 94: Furniture\n  \"9403\": {\n    description: \"Other furniture and parts thereof\",\n    category: \"Furniture\",\n    typical_keywords: [\"furniture\", \"desk\", \"table\", \"chair\", \"cabinet\"]\n  }\n};\n\n// EMBEDDED DUTY RATE TABLE (by destination country and HS chapter)\nconst dutyRates = {\n  \"India\": {\n    \"30\": { rate: 10, description: \"Pharmaceuticals - Basic customs duty\" },\n    \"84\": { rate: 7.5, description: \"Machinery - Concessional rate\" },\n    \"85\": { rate: 10, description: \"Electrical equipment\" },\n    \"61\": { rate: 20, description: \"Textiles and garments\" },\n    \"73\": { rate: 10, description: \"Iron and steel articles\" },\n    \"94\": { rate: 20, description: \"Furniture\" },\n    \"default\": { rate: 15, description: \"General goods\" }\n  },\n  \"USA\": {\n    \"30\": { rate: 0, description: \"Pharmaceuticals - Duty free\" },\n    \"84\": { rate: 0, description: \"Computers - Duty free\" },\n    \"85\": { rate: 0, description: \"Electronics - Duty free\" },\n    \"61\": { rate: 16.5, description: \"Textiles\" },\n    \"73\": { rate: 0, description: \"Steel products - Duty free\" },\n    \"94\": { rate: 0, description: \"Furniture - Duty free\" },\n    \"default\": { rate: 3.5, description: \"General goods\" }\n  },\n  \"UK\": {\n    \"30\": { rate: 0, description: \"Pharmaceuticals - Duty free\" },\n    \"84\": { rate: 0, description: \"Machinery - Duty free\" },\n    \"85\": { rate: 0, description: \"Electronics - Duty free\" },\n    \"61\": { rate: 12, description: \"Textiles\" },\n    \"73\": { rate: 0, description: \"Steel - Duty free\" },\n    \"94\": { rate: 0, description: \"Furniture - Duty free\" },\n    \"default\": { rate: 2.5, description: \"General goods\" }\n  },\n  \"Singapore\": {\n    \"30\": { rate: 0, description: \"Pharmaceuticals - Duty free\" },\n    \"84\": { rate: 0, description: \"All machinery - Duty free\" },\n    \"85\": { rate: 0, description: \"All electronics - Duty free\" },\n    \"61\": { rate: 0, description: \"All textiles - Duty free\" },\n    \"73\": { rate: 0, description: \"All steel - Duty free\" },\n    \"94\": { rate: 0, description: \"All furniture - Duty free\" },\n    \"default\": { rate: 0, description: \"Duty free port\" }\n  },\n  \"default\": {\n    \"default\": { rate: 10, description: \"Standard rate\" }\n  }\n};\n\n// RESTRICTED/PROHIBITED ITEMS DATABASE\nconst restrictedItems = {\n  \"India\": [\n    { keywords: [\"narcotic\", \"opium\", \"cocaine\"], restriction: \"PROHIBITED - Narcotic substances\" },\n    { keywords: [\"weapon\", \"arms\", \"ammunition\"], restriction: \"RESTRICTED - Requires defense license\" },\n    { keywords: [\"satellite phone\"], restriction: \"RESTRICTED - Requires telecom license\" },\n    { keywords: [\"wildlife\", \"ivory\", \"fur\"], restriction: \"PROHIBITED - Wildlife protection act\" }\n  ],\n  \"USA\": [\n    { keywords: [\"cuban\", \"cuba\"], restriction: \"RESTRICTED - Embargo restrictions\" },\n    { keywords: [\"counterfeit\", \"fake\", \"replica\"], restriction: \"PROHIBITED - IPR violation\" },\n    { keywords: [\"food\", \"meat\", \"dairy\"], restriction: \"RESTRICTED - FDA approval required\" }\n  ]\n};\n\n// Extract BoL data\nconst bolNumber = bolData.BoL_Number || 'UNKNOWN';\nconst commodityDesc = (bolData.Commodity_Description || '').toLowerCase();\nconst declaredHSCode = (bolData.HS_Code || '').replace(/\\./g, '').substring(0, 4);\nconst countryOfOrigin = bolData.Country_of_Origin || 'Unknown';\nconst destinationCountry = bolData.Destination_Country || 'Unknown';\nconst declaredValue = extractNumber(bolData.Declared_Value_USD);\nconst grossWeight = extractNumber(bolData.Gross_Weight_KG);\nconst numPackages = extractNumber(bolData.Number_of_Packages);\n\n// INTELLIGENCE 1: Validate HS Code against commodity description\nlet hsCodeValidation = 'Unknown';\nlet suggestedHSCode = declaredHSCode;\nlet hsCodeConfidence = 'Low';\n\nif (declaredHSCode && hsCodeDatabase[declaredHSCode]) {\n  const hsInfo = hsCodeDatabase[declaredHSCode];\n  const keywordsMatch = hsInfo.typical_keywords.some(keyword => \n    commodityDesc.includes(keyword)\n  );\n  \n  if (keywordsMatch) {\n    hsCodeValidation = 'Valid - Matches commodity';\n    hsCodeConfidence = 'High';\n  } else {\n    hsCodeValidation = 'Questionable - Description mismatch';\n    hsCodeConfidence = 'Low';\n  }\n} else if (declaredHSCode) {\n  hsCodeValidation = 'Unknown HS Code - Manual review needed';\n  hsCodeConfidence = 'Unknown';\n} else {\n  // Try to suggest HS code based on commodity description\n  for (const [code, info] of Object.entries(hsCodeDatabase)) {\n    const matches = info.typical_keywords.filter(keyword => \n      commodityDesc.includes(keyword)\n    );\n    if (matches.length > 0) {\n      suggestedHSCode = code;\n      hsCodeValidation = `No HS Code provided - Suggest ${code}`;\n      hsCodeConfidence = 'Medium';\n      break;\n    }\n  }\n}\n\n// INTELLIGENCE 2: Calculate duty rate\nconst hsChapter = String(suggestedHSCode).substring(0, 2);\nconst countryRates = dutyRates[destinationCountry] || dutyRates['default'];\nconst dutyInfo = countryRates[hsChapter] || countryRates['default'];\nconst dutyRate = dutyInfo.rate;\nconst dutyDescription = dutyInfo.description;\n\n// Calculate estimated duty amount\nconst estimatedDuty = (declaredValue * dutyRate) / 100;\n\n// INTELLIGENCE 3: Check for undervaluation (value per kg analysis)\nlet valuationStatus = 'Normal';\nlet valuationWarning = '';\n\nif (grossWeight > 0 && declaredValue > 0) {\n  const valuePerKg = declaredValue / grossWeight;\n  \n  // Typical value ranges by category (USD per kg)\n  const typicalValues = {\n    \"Pharmaceuticals\": { min: 5, max: 5000 },\n    \"Electronics\": { min: 20, max: 1000 },\n    \"Textiles\": { min: 5, max: 50 },\n    \"Industrial\": { min: 2, max: 100 },\n    \"Furniture\": { min: 3, max: 50 }\n  };\n  \n  const hsInfo = hsCodeDatabase[suggestedHSCode];\n  if (hsInfo && typicalValues[hsInfo.category]) {\n    const range = typicalValues[hsInfo.category];\n    \n    if (valuePerKg < range.min) {\n      valuationStatus = 'Suspiciously Low';\n      valuationWarning = `Value per kg ($${valuePerKg.toFixed(2)}) is below typical range ($${range.min}-$${range.max}) for ${hsInfo.category}`;\n    } else if (valuePerKg > range.max) {\n      valuationStatus = 'Suspiciously High';\n      valuationWarning = `Value per kg ($${valuePerKg.toFixed(2)}) exceeds typical range ($${range.min}-$${range.max}) for ${hsInfo.category}`;\n    } else {\n      valuationStatus = 'Normal';\n      valuationWarning = `Value per kg ($${valuePerKg.toFixed(2)}) within expected range`;\n    }\n  }\n}\n\n// INTELLIGENCE 4: Check for restricted/prohibited items\nlet restrictionStatus = 'No restrictions';\nlet restrictionDetails = '';\n\nconst countryRestrictions = restrictedItems[destinationCountry] || [];\nfor (const item of countryRestrictions) {\n  const hasRestrictedKeyword = item.keywords.some(keyword => \n    commodityDesc.includes(keyword)\n  );\n  if (hasRestrictedKeyword) {\n    restrictionStatus = 'RESTRICTED/PROHIBITED';\n    restrictionDetails = item.restriction;\n    break;\n  }\n}\n\n// INTELLIGENCE 5: Overall compliance risk assessment\nlet complianceRisk = 'Low';\nlet riskFactors = [];\n\nif (hsCodeValidation.includes('Questionable') || hsCodeValidation.includes('Unknown')) {\n  riskFactors.push('HS Code validation failed');\n}\n\nif (valuationStatus.includes('Suspicious')) {\n  riskFactors.push('Unusual valuation detected');\n}\n\nif (restrictionStatus.includes('RESTRICTED')) {\n  riskFactors.push('Restricted/prohibited item');\n}\n\nif (!declaredHSCode) {\n  riskFactors.push('Missing HS Code');\n}\n\nif (riskFactors.length >= 3) {\n  complianceRisk = 'Critical';\n} else if (riskFactors.length >= 2) {\n  complianceRisk = 'High';\n} else if (riskFactors.length === 1) {\n  complianceRisk = 'Medium';\n} else {\n  complianceRisk = 'Low';\n}\n\n// Generate recommendations\nlet recommendations = [];\n\nif (hsCodeValidation.includes('Suggest')) {\n  recommendations.push(`Add HS Code ${suggestedHSCode} to declaration`);\n}\n\nif (hsCodeValidation.includes('Questionable')) {\n  recommendations.push('Verify HS Code accuracy with customs broker');\n}\n\nif (valuationStatus.includes('Suspicious')) {\n  recommendations.push('Provide detailed invoice breakdown to justify valuation');\n}\n\nif (restrictionStatus.includes('RESTRICTED')) {\n  recommendations.push(`URGENT: Obtain required licenses - ${restrictionDetails}`);\n}\n\nif (dutyRate === 0) {\n  recommendations.push('Duty-free entry - Ensure proper documentation for exemption');\n} else if (estimatedDuty > 10000) {\n  recommendations.push('High duty amount - Consider duty deferral or bonded warehouse');\n}\n\nif (recommendations.length === 0) {\n  recommendations.push('No immediate action required - Standard customs clearance');\n}\n\nreturn {\n  json: {\n    BoL_Number: bolNumber,\n    Commodity_Description: bolData.Commodity_Description || 'Not provided',\n    Declared_HS_Code: bolData.HS_Code || 'Not provided',\n    Validated_HS_Code: String(suggestedHSCode),\n    HS_Code_Validation: hsCodeValidation,\n    HS_Code_Confidence: hsCodeConfidence,\n    Country_of_Origin: countryOfOrigin,\n    Destination_Country: destinationCountry,\n    Declared_Value_USD: declaredValue.toFixed(2),\n    Gross_Weight_KG: grossWeight.toFixed(2),\n    Value_Per_KG: grossWeight > 0 ? (declaredValue / grossWeight).toFixed(2) : 'N/A',\n    Valuation_Status: valuationStatus,\n    Valuation_Warning: valuationWarning || 'None',\n    Applicable_Duty_Rate: dutyRate + '%',\n    Duty_Description: dutyDescription,\n    Estimated_Duty_USD: estimatedDuty.toFixed(2),\n    Restriction_Status: restrictionStatus,\n    Restriction_Details: restrictionDetails || 'None',\n    Compliance_Risk_Level: complianceRisk,\n    Risk_Factors: riskFactors.join('; ') || 'None',\n    Recommendations: recommendations.join('; '),\n    Processing_Timestamp: new Date().toISOString()\n  }\n};"
      },
      "id": "c22124fc-7a3e-437a-ac2d-ecf8cc810512",
      "name": "Customs Intelligence Analyzer",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        608,
        -144
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "1nKGkrFXpWBeTJd2_xRTg5Gn1-msvl9YXn7rB6WDflwY",
          "mode": "list",
          "cachedResultName": "Case_49_BoL_Reconciliation_Log",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1nKGkrFXpWBeTJd2_xRTg5Gn1-msvl9YXn7rB6WDflwY/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1nKGkrFXpWBeTJd2_xRTg5Gn1-msvl9YXn7rB6WDflwY/edit#gid=0"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [
            {
              "id": "BoL_Number",
              "displayName": "BoL_Number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Commodity_Description",
              "displayName": "Commodity_Description",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Declared_HS_Code",
              "displayName": "Declared_HS_Code",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Validated_HS_Code",
              "displayName": "Validated_HS_Code",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "HS_Code_Validation",
              "displayName": "HS_Code_Validation",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "HS_Code_Confidence",
              "displayName": "HS_Code_Confidence",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Country_of_Origin",
              "displayName": "Country_of_Origin",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Destination_Country",
              "displayName": "Destination_Country",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Declared_Value_USD",
              "displayName": "Declared_Value_USD",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Gross_Weight_KG",
              "displayName": "Gross_Weight_KG",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Value_Per_KG",
              "displayName": "Value_Per_KG",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Valuation_Status",
              "displayName": "Valuation_Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Valuation_Warning",
              "displayName": "Valuation_Warning",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Applicable_Duty_Rate",
              "displayName": "Applicable_Duty_Rate",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Duty_Description",
              "displayName": "Duty_Description",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Estimated_Duty_USD",
              "displayName": "Estimated_Duty_USD",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Restriction_Status",
              "displayName": "Restriction_Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Restriction_Details",
              "displayName": "Restriction_Details",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Compliance_Risk_Level",
              "displayName": "Compliance_Risk_Level",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Risk_Factors",
              "displayName": "Risk_Factors",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Recommendations",
              "displayName": "Recommendations",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Processing_Timestamp",
              "displayName": "Processing_Timestamp",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "29863f63-5bfb-4e29-bfe5-af7bcad0e553",
      "name": "Log to Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        800,
        -144
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "LOs2dbk9lby0NfDM",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const data = $input.first().json;\n\nconst bolNumber = data.BoL_Number || 'Unknown';\nconst complianceRisk = data.Compliance_Risk_Level || 'Unknown';\nconst estimatedDuty = data.Estimated_Duty_USD || '0.00';\nconst restrictionStatus = data.Restriction_Status || 'Unknown';\n\nconst riskEmoji = complianceRisk === 'Critical' ? '🚨' : \n                   complianceRisk === 'High' ? '⚠️' : \n                   complianceRisk === 'Medium' ? '⚡' : '✅';\n\nconst emailSubject = `Customs Analysis Alert - BoL ${bolNumber} [${complianceRisk} Risk]`;\n\nconst emailBody = `Dear Customs Broker Team,\n\nA Bill of Lading has been analyzed for customs classification and duty estimation.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n📋 SHIPMENT DETAILS\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nBoL Number: ${data.BoL_Number}\nCommodity: ${data.Commodity_Description}\nOrigin: ${data.Country_of_Origin}\nDestination: ${data.Destination_Country}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n🏷️ HS CODE CLASSIFICATION\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nDeclared HS Code: ${data.Declared_HS_Code}\nValidated HS Code: ${data.Validated_HS_Code}\nValidation Status: ${data.HS_Code_Validation}\nConfidence Level: ${data.HS_Code_Confidence}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n💰 VALUATION ANALYSIS\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nDeclared Value: $${data.Declared_Value_USD}\nGross Weight: ${data.Gross_Weight_KG} kg\nValue per KG: $${data.Value_Per_KG}\nValuation Status: ${data.Valuation_Status}\n${data.Valuation_Warning !== 'None' ? '⚠️ Warning: ' + data.Valuation_Warning : ''}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n💵 DUTY ESTIMATION\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nApplicable Duty Rate: ${data.Applicable_Duty_Rate}\nDuty Type: ${data.Duty_Description}\nEstimated Duty Amount: $${estimatedDuty}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${restrictionStatus.includes('RESTRICTED') ? '🚫' : '✅'} RESTRICTIONS CHECK\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nStatus: ${restrictionStatus}\n${data.Restriction_Details !== 'None' ? '⚠️ ALERT: ' + data.Restriction_Details : 'No restrictions identified'}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${riskEmoji} COMPLIANCE RISK ASSESSMENT\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nRisk Level: ${complianceRisk}\nRisk Factors: ${data.Risk_Factors}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n✅ RECOMMENDED ACTIONS\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${data.Recommendations}\n\n${\n  complianceRisk === 'Critical' || complianceRisk === 'High'\n    ? '⚠️ URGENT ACTION REQUIRED - Do not proceed with customs clearance until issues are resolved.'\n    : complianceRisk === 'Medium'\n    ? '⚡ REVIEW RECOMMENDED - Address flagged items before customs submission.'\n    : '✅ LOW RISK - Proceed with standard customs clearance process.'\n}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nProcessed: ${data.Processing_Timestamp}\n\nThis is an automated analysis from the Customs Intelligence System.\nFor queries, contact the Trade Compliance Team.\n\nBest regards,\nAutomated Customs Analyzer`;\n\nreturn {\n  json: {\n    email_subject: emailSubject,\n    email_body: emailBody,\n    recipient_email: 'customs.broker@company.com',\n    cc_email: 'trade.compliance@company.com',\n    bol_number: bolNumber,\n    compliance_risk: complianceRisk,\n    estimated_duty: estimatedDuty\n  }\n};"
      },
      "id": "c06fd457-69fc-45cc-8610-d78eb649767b",
      "name": "Generate Email Summary",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        992,
        -144
      ]
    },
    {
      "parameters": {
        "sendTo": "={{ $json.recipient_email }}",
        "subject": "={{ $json.email_subject }}",
        "emailType": "text",
        "message": "={{ $json.email_body }}",
        "options": {}
      },
      "id": "20c86fd6-84c1-4df2-ae78-7c50a97545c2",
      "name": "Send Email via Gmail",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1184,
        -144
      ],
      "webhookId": "439bb3f4-fd99-494d-9e3c-fdee63a37135",
      "credentials": {
        "gmailOAuth2": {
          "id": "cyqCGWcggZNMcSOv",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list"
        },
        "builtInTools": {},
        "options": {}
      },
      "id": "aabb2c62-d357-4516-baef-2d0b7a84766d",
      "name": "OpenAI GPT-4o Mini",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        304,
        48
      ],
      "credentials": {
        "openAiApi": {
          "id": "ICwxUBbatsF2sDvy",
          "name": "OpenAi account"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "Monitor BoL Upload Folder": {
      "main": [
        [
          {
            "node": "Download BoL Document",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download BoL Document": {
      "main": [
        [
          {
            "node": "Upload to Parser",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload to Parser": {
      "main": [
        [
          {
            "node": "Wait for Parsing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait for Parsing": {
      "main": [
        [
          {
            "node": "Check Parsing Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Parsing Status": {
      "main": [
        [
          {
            "node": "Route Based on Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route Based on Status": {
      "main": [
        [
          {
            "node": "Extract Parsed Content",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Wait for Parsing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Parsed Content": {
      "main": [
        [
          {
            "node": "AI Data Extractor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Data Extractor": {
      "main": [
        [
          {
            "node": "Customs Intelligence Analyzer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Customs Intelligence Analyzer": {
      "main": [
        [
          {
            "node": "Log to Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log to Google Sheets": {
      "main": [
        [
          {
            "node": "Generate Email Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Email Summary": {
      "main": [
        [
          {
            "node": "Send Email via Gmail",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI GPT-4o Mini": {
      "ai_languageModel": [
        [
          {
            "node": "AI Data Extractor",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "adef9bc2-a87e-4595-883f-9b54e300ab12",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "3a43da28588548e21903e71cf1dc3ddd65c24bf0c62e7e4b77542ffe87ad79c6"
  },
  "id": "mpOztMAUch9Ao53d",
  "tags": []
}